<?php

namespace app\common\validate\tyyh;

class UserWallet extends Base
{
	/**
     * 验证规则
     */
    protected $rule = [
        'lock'                => 'require',
        'id'                  => 'require',
        'money'               => 'require|gt:0',
        'aid'                 => 'activity',
        'uid'                 => 'require',
        'oid'                 => 'require'
    ];

    /**
     * 提示消息
     */
    protected $message = [
        'lock.require'                  => '验证规则场景不存在',
        'id.require'                    => '退款单ID不能为空',
        'id.isUser'                     => '退款单不属于您',
        'id.isCancel'                   => '退款单已经完成，无法取消',
        'money.require'                 => '充值金额不能为空',
        'money.gt'                      => '充值金额必须大于0',
        'aid.activity'                  => '活动ID不合法',
        'uid.require'                   => '用户ID不能为空',
        'oid.require'                   => '订单ID不能为空',
        'oid.isUser'                    => '订单ID不属于您',
        'oid.isPay'                     => '该订单还没有支付',
        'oid.isRefund'                  => '该订单已经有了退款单'

    ];
    /**
     * 验证场景
     */
    protected $scene = [
    	'balance_order'              => ['money'],
        'user_wallet_balance_refund' => ['uid', 'oid' => 'require|isUser:tyyh\\UserWalletBalanceOrder|isPay|isRefund'],
        'cancel_balance_refund'      => ['uid', 'id' => 'require|isUser:tyyh\\UserWalletBalanceRefund|isCancel']
    ];

    // 验证活动ID
    protected function activity($value, $rule, $data = []) {
        return in_array($value, [0, 1]);
    }

    // 验证订单是否已经支付
    protected function isPay($value, $rule, $data = []) {
        $order = loader()->loadAny('only', 'tyyh\\UserWalletBalanceOrder')->get_row($data['oid']);
        return $order && $order['paytime'] > 0;
    }

    // 验证订单是否已经有了退款单
    protected function isRefund($value, $rule, $data = []) {
        $model = loader()->loadModel('tyyh\\UserWalletBalanceRefund');
        $model->where('oid', $data['oid']);
        $model->where('status', 'neq', loadEnum('UserWalletBalanceRefundStatus')->code2key('yiquxiao'));
        $count = $model->count();
        return $count == 0;
    }

    // 验证退款单是否可以取消
    protected function isCancel($value, $rule, $data=[]) {
        $row = loader()->loadAny('only', 'tyyh\\UserWalletBalanceRefund')->get_row($data['id']);
        return $row->status == loadEnum('UserWalletBalanceRefundStatus')->code2key('daishenhe');
    }
}
